<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/19 0019
 * Time: 10:31
 */

namespace frontend\controllers;
// header("Access-Control-Allow-Origin:http://medicals.qingguo188.com");
// header("Access-Control-Allow-Origin:http://localhost:8080");
header("Access-Control-Allow-Methods:POST,GET");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Credentials: true");
use common\models\User;
use common\models\UserRecipe;
use common\models\UserSecondary;
use common\models\UserDrug;
use common\models\UserDrugWarehouse;
use common\models\UserSupplier;
use common\models\UserPatient;
use common\models\UserPatientSymptom;
use common\models\UserRecipeRecord;
use Yii;
// use yii\web\Controller;
use yii\data\Pagination;
use frontend\controllers\BaseController;
/**
 * User controller
 */
class UserPatientController extends BaseController
{

    public function beforeAction($action)
    {
        if ($action->id == 'searchpatient'|| $action->id == 'confirmpatientdrug' || $action->id == 'showundealrecipe' ||$action->id == 'searchpatientrecord' ||$action->id == 'searchdrug'||$action->id == 'druginfo' ||$action->id == 'addprescription'||$action->id == 'adddrug') {
            $this->enableCsrfValidation = false;
        }
        return parent::beforeAction($action);
    }
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [

        ];

    }
    /**
     * 搜索患者信息以及记录信息
     *
     * return json
     */
    public function actionSearchpatient()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                //获得当前登录的用户
                $data = $this->doifuserid($data1);
                //搜索患者的信息
                $arr = [];
                $patientInfo = UserPatient::find()->where("user_id = :user_id and status = :status and patient like '%".$data1['patient_name']."%'",[":user_id"=>$data['id'],":status"=>1])->all();
                if($patientInfo){
                    $count= count($patientInfo);
                    for($i = 0;$i<$count;$i++){
                        $arr[$i]['id'] = $patientInfo[$i]['id'];
                        $arr[$i]['patient'] = $patientInfo[$i]['patient'];
                        $arr[$i]['age'] = $patientInfo[$i]['age'];
                        $arr[$i]['sex'] = $patientInfo[$i]['sex'];
                        $arr[$i]['site'] = $patientInfo[$i]['site'];
                        $arr[$i]['site'] = $patientInfo[$i]['site'];
                        $arr[$i]['card'] = $patientInfo[$i]['card'];
                        $arr[$i]['phone'] = $patientInfo[$i]['phone'];
                    }
                }
                return $this->getjson(1,$arr);
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * 根据选择的患者查询对应的接诊记录
     *
     * return json
     */
    public function actionSearchpatientrecord()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                //搜索患者的接诊信息
                $arr = [];
                if($data1['id']){
                    $record = UserPatientSymptom::find()->where('status = :status and user_patient_id = :id',[":status"=>1,":id"=>$data1['id']])->all();
                    //获得姓名,就诊时间,诊断
                    if($record){
                        $count = count($record);
                        for($i = 0;$i < $count;$i++){
                            $patientInfo = UserPatient::find()->where("id = :id and status = :status ",[":id"=>$data1['id'],":status"=>1])->one();
                            if($patientInfo){
                                $arr['list'][$i]['patient_name'] = $patientInfo['patient'];
                                $arr['list'][$i]['time'] = $record[$i]['create_time'];
                                $arr['list'][$i]['symptom'] = $record[$i]['symptom'];
                            }
                        }
                    }
                    //获得患者信息
                    $patient = UserPatient::find()->where('status = :status and id = :id',[":status"=>1,":id"=>$data1['id']])->one();
                    if($patient){
                        $arr['patient']['id'] = $patient['id'];
                        $arr['patient']['name'] = $patient['patient'];
                        $arr['patient']['sex'] = $patient['sex'];
                        $arr['patient']['age'] = $patient['age'];
                        $arr['patient']['site'] = $patient['site'];
                        $arr['patient']['phone'] = $patient['phone'];
                        $arr['patient']['card'] = $patient['card'];
                    }else{
                        $arr['patient'] = '';
                    }
                }
                return $this->getjson(1,$arr);
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * 搜索药品字典的名称
     *
     * return json
     */
    public function actionSearchdrug()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                //获得当前登录的用户的顶级用户的id
                $data = $this->doifuserid($data1);
                $arr = [];
                //搜索药品的信息
                $namelist = UserDrug::find()->where("user_id = :user_id and name like '%".$data1['name']."%'",[":user_id" => $data['id']])->all();
                if($namelist){
                    $count = count($namelist);
                    for($i = 0;$i < $count;$i++){
                        //判断该用户的药品库中是否已有药品
                        $userdrugwarehouse = UserDrugWarehouse::find()->where("num > 0  and user_id = :user_id and user_drug_id = :user_drug_id and  status = :status",[':status'=>1,':user_drug_id'=>$namelist[$i]['id'],"user_id"=>$data['id']])->all();
                        if(count($userdrugwarehouse)){
                            $arr[$i]['id'] = $namelist[$i]['id'];
                            $arr[$i]['name'] = $namelist[$i]['name'];
                        }
                    }
                }
                return $this->getjson(1,$arr);
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * 获得详细的药品信息
     * return json
     */
    public function actionDruginfo()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                $arr = [];
                //判断用户是不是二级用户,如果是获得一级用户的id
                $data = $this->doifuserid($data1);
                //先查询用户字典的信息   接着查询药品的信息
                $druginfo = UserDrug::find()->where("id = :id and user_id = :user_id",['id'=>$data1['drug_id'],":user_id"=>$data['id']])->one();
                if($druginfo){
                    //(1)获得名称,规格
                    $arr['name'] = $druginfo['name'];
                    $arr['specification'] = $druginfo['specification'];
                    $arr['drug_id'] = $druginfo['id'];
                    $arr['yfyl'] = '';
                    //(2)生产厂家
                    $supplier = UserSupplier::find()->where('user_id = :user_id and id = :id',[':user_id'=>$data['id'],":id"=>$druginfo['vender_id']])->one();
                    if($supplier){
                        $arr['supplier'] = $supplier['name'];

                    }else{
                        $arr['supplier'] = '';
                    }
                    //(3)统计总的库存
                    //(4)获得最新的报价   获得最早入库的商品的id
                    $userdrugs = UserDrugWarehouse::find()->where("user_id = :user_id and user_drug_id = :user_drug_id",[':user_id'=>$data['id'],'user_drug_id'=>$druginfo['id']])->orderBy('id desc')->all();
                    $userdrug = UserDrugWarehouse::find()->where("user_id = :user_id and user_drug_id = :user_drug_id",[':user_id'=>$data['id'],'user_drug_id'=>$druginfo['id']])->orderBy('id asc')->one();
                    if($userdrug){
                        $arr['drug_warehouse_id'] = $userdrug['id'];
                        $arr['price'] = $userdrug['out_price'];
                    }else{
                        $arr['drug_warehouse_id'] = '';
                        $arr['latest_out_price'] = '';
                    }
                    if($userdrugs){
                        $arr['num'] = 0;
                        foreach($userdrugs as $key=>$val){
                            $arr['num'] += $val['num'];
                        }
                    }else{
                        $arr['num'] = 0;
                    }
                }
                return $this->getjson(1,$arr);
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }
    /**
     * 添加处方,并返回
     * return json
     */
    public function actionAddprescription()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                $time = date('Y-m-d H:i:s',strtotime('now'));
                //(1)判断是否是2级用户,是的话获得一级用户的id
                if($data1['level'] == 2){
                    $userInfo = UserSecondary::find()->where('id = :id and status = :status',[':id'=>$data1['id'],'status'=>1])->one();
                    if($userInfo){
                        $data1['first_id'] = $userInfo['user_id'];
                        $data1['second_id'] = $data1['id'];

                    }else{
                        return $this->getjson(0,'参数错误');
                    }
                }else{
                    $data1['first_id'] = $data1['id'];
                    $data1['second_id'] = '';
                }
                //(2)需要首先判断患者是否存在,不存在添加患者
                $patient = new UserPatient();
                if(!$data1['patient_id']){
                    //添加
                    $patient->user_id = $data1['first_id'];
                    $patient->patient = $data1['name'];
                    $patient->age = $data1['age'];
                    $patient->sex = $data1['sex'];
                    $patient->phone = $data1['phone'];
                    $patient->card = $data1['card'];
                    $patient->site = $data1['site'];
                    $patient->create_time = $time;
                }else{
                    //更新
                    $patient = $patient->findOne($data1['patient_id']);
                    $patient->patient = $data1['name'];
                    $patient->age = $data1['age'];
                    $patient->sex = $data1['sex'];
                    $patient->phone = $data1['phone'];
                    $patient->card = $data1['card'];
                    $patient->site = $data1['site'];
                }
                if(!$patient->save()){
                    return $this->getjson(0,'添加失败,请重试');
                }
                //(3)添加患者病例详细信息 处方的信息
                $symptom = new UserPatientSymptom();
                $symptom->user_id = $data1['first_id'];
                $symptom->user_patient_id = $patient->id;
                $symptom->symptom = $data1['symptom'];
                $symptom->temperature = $data1['temperature'];
                $symptom->pulse = $data1['pulse'];
                $symptom->low_blood_pressure = $data1['low_blood_pressure'];
                $symptom->high_blood_pressure = $data1['high_blood_pressure'];
                $symptom->age = $patient->age;
                $symptom->create_time = $time;
                if(!$symptom->save()){
                    return $this->getjson(0,'添加失败,请重试');
                }
                $user_patient_symptom_id = $symptom->id;
                //(4)添加总的信息
                $arr1 = json_decode($data1['arr'],true);
                $count = count($arr1);
                if(!$count){
                    return $this->getjson(0,'没有添加药品');
                }else{
                    $total = 0;
                    foreach($arr1 as $key=>$val){
                        $total += $val['num']*$val['price'];
                    }
                }
                $user_recipe = new UserRecipe();
                $user_recipe->user_id = $data1['first_id'];
                $user_recipe->user_patient_symptom_id = $user_patient_symptom_id;
                $user_recipe->price = $total;
                $user_recipe->create_time = $time;
                if(!$user_recipe->save()){
                    return $this->getjson(0,'添加失败,请重试');
                }
                $user_recipe_id = $user_recipe->id;
                //(5)添加处方中的药品信息
                foreach($arr1 as $key=>$val){
                    $model = new UserRecipeRecord();
                    $model->user_id = $data1['first_id'];
                    $model->user_secondary_id = $data1['second_id'];
                    $model->user_recipe_id = $user_recipe_id;
                    $model->user_drug_warehouse_id = $val['drug_warehouse_id'];
                    $model->num = $val['num'];
                    $model->price = $val['price'];
                    $model->employs = $val['yfyl'];
                    $model->save();
                }

                //(6)获得未处理的处方个数

                $undeal_recipe = new UserRecipe();
                $undeallist = $undeal_recipe::find()->where('is_deal = :deal and user_id = :user_id',[':deal'=>0,':user_id'=>$data1['first_id']])->all();
                $count = count($undeallist);
                return $this->getjson(1,$count);
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * 获得为处理的处方信息
     * return json
     */
    public function actionShowundealrecipe()
    {
        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                //(1)判断是否是2级用户,是的话获得一级用户的id
                if($data1['level'] == 2){
                    $userInfo = UserSecondary::find()->where('id = :id and status = :status',[':id'=>$data1['id'],'status'=>1])->one();
                    if($userInfo){
                        $data1['first_id'] = $userInfo['user_id'];
                        $data1['second_id'] = $data1['id'];

                    }else{
                        return $this->getjson(0,'参数错误');
                    }
                }else{
                    $data1['first_id'] = $data1['id'];
                    $data1['second_id'] = '';
                }
                $arr = [];
                $undeal_recipe = new UserRecipe();
                $undeallist = $undeal_recipe::find()->where('is_deal = :deal and user_id = :user_id',[':deal'=>0,':user_id'=>$data1['first_id']])->all();
                $count = count($undeallist);
                if($count){
                    for($i = 0;$i<$count;$i++){
                        $user_patient_symptom_id = $undeallist[$i]['user_patient_symptom_id'];
                        //(1)获得处方患者症状信息
                        $user_patient_symptom = UserPatientSymptom::findOne($user_patient_symptom_id);
                        $user_patient_id = $user_patient_symptom->user_patient_id;
                        //(2)获得处方的药品信息
                        $user_recipe_recode = UserRecipeRecord::find()->where('user_id = :user_id and user_recipe_id = :user_recipe_id',[':user_id'=>$data1['first_id'],':user_recipe_id'=>$undeallist[$i]['id']])->all();
                        foreach($user_recipe_recode as $key=>$val){
                            $user_drug_info = UserDrugWarehouse::findOne($val['user_drug_warehouse_id']);
                            $drug_info = UserDrug::findOne($user_drug_info['user_drug_id']);
                            $arr[$i]['drug'][$key]['drug_warehouse_id'] = $user_drug_info['id'];
                            $arr[$i]['drug'][$key]['drug_name'] = $drug_info['name'];
                            $arr[$i]['drug'][$key]['num'] = $val['num'];
                            $arr[$i]['drug'][$key]['yfyl'] = $val['employs'];
                            $arr[$i]['drug'][$key]['price'] = $val['price'];
                        }

                        //(3)获得处方的患者信息
                        $user_patient_info = UserPatient::findOne($user_patient_id);
                        $arr[$i]['patient']['patient_id'] = $user_patient_info['id'];
                        $arr[$i]['patient']['patient_recipe_id'] = $undeallist[$i]['id'];
                        $arr[$i]['patient']['name'] = $user_patient_info['patient'];
                        $arr[$i]['patient']['create_time'] = $user_patient_info['create_time'];
                        $arr[$i]['patient']['status'] = '未取药';
                    }
                }
                return $this->getjson(1,$arr);
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * 确认取药
     * return json
     */
    public function actionConfirmpatientdrug()
    {
        //(2)减少药的库存

        if(Yii::$app->request->isPost){
            $data1 = Yii::$app->request->post();
            if($data1){
                //(1)判断是否是2级用户,是的话获得一级用户的id
                if($data1['level'] == 2){
                    $userInfo = UserSecondary::find()->where('id = :id and status = :status',[':id'=>$data1['id'],'status'=>1])->one();
                    if($userInfo){
                        $data1['first_id'] = $userInfo['user_id'];
                        $data1['second_id'] = $data1['id'];

                    }else{
                        return $this->getjson(0,'参数错误');
                    }
                }else{
                    $data1['first_id'] = $data1['id'];
                    $data1['second_id'] = '';
                }
                //(1)更新患者记录表中的状态
                $user_recipe = UserRecipe::findOne($data1['patient_recipe_id']);
                if(!$user_recipe){
                    return $this->getjson(0,'失败');
                }
                $user_recipe->is_deal = 1;
                if(!$user_recipe->save()){
                    return $this->getjson(0,'更新失败');
                }

                //(2)减少药的库存
                $arr = json_decode($data1['arr'],true);
                foreach($arr as $key=>$val){
                    $user_drug_warehouser = UserDrugWarehouse::findOne($val['drug_warehouse_id']);
                    //判断这次入库的库存是否够
                    if($user_drug_warehouser['num'] > $val['num']){
                        $user_drug_warehouser->num = $user_drug_warehouser->num - $val['num'];
                        $user_drug_warehouser->save();
                    }else{
                        //这个入库的药品库存不够,去看有没其他批次的
                        $user_drug_id = $user_drug_warehouser->user_drug_id;
                        $user_drug_warehouserlist = UserDrugWarehouse::find()->where('user_drug_id = :user_drug_id and user_id = :user_id',[':user_drug_id'=>$user_drug_id,':user_id'=>$data1['first_id']])->orderBy('id asc')->all();
                        $remain_num = $val['num'];
                        foreach($user_drug_warehouserlist as $key1=>$val1){
                            $remain_num = $remain_num - $val1['num'];
                            if($remain_num > 0){
                                //卖出去的比库存多
                                $user_drug_warehouser1 = UserDrugWarehouse::findOne($val1['id']);
                                $user_drug_warehouser1->num = 0;
                                $user_drug_warehouser1->save();
                            }else{
                                //卖出去的库存少
                                $user_drug_warehouser1 = UserDrugWarehouse::findOne($val1['id']);
                                $user_drug_warehouser1->num = -$remain_num;
                                $user_drug_warehouser1->save();
                            }
                        }
                    }
                }
                return $this->getjson(1,'成功');
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }


    /**
     * 判断是否是二级用户,是的话获得一级用户的id
     */
    public  function  doifuserid($data)
    {
        if($data['level'] == 2){
            $userInfo = UserSecondary::find()->where('id = :id',[':id'=>$data['id']])->one();
            $data['id'] = $userInfo['user_id'];
            if(!$userInfo){
                return $this->getjson(0, '获取用户信息失败');
            }
            $data['id'] = $userInfo['user_id'];
        }
        if(!$data['id']){
            return $this->getjson(0, '用户尚未登录');
        }
        return  $data;
    }
}





















